import { defineStore } from 'pinia'

export default defineStore('useAdmin', {
    state: () => ({
        admin: {} as AdminModel,
        token: null as string | null,
        expires: null as number | null,
        timer: 0 as number
    }),
    getters: {
        getToken(state) {
            if (!state.expires || (Date.now() - state.timer >= state.expires * 1000)) {
                state.token = ""
                return ""
            } else {
                return state.token
            }
        }
    },
    actions: {
        setToken(token: string, expires: number) {
            this.token = token
            this.expires = expires
            this.timer = Date.now()
        },
        setAdmin(admin: AdminModel) {
            this.admin = admin
        },
        async logout() {
            await this.$reset()
        }
    },
    persist: true
})